package com.vtest.quartz.controller;

import com.vtest.quartz.domain.job.SysJob;
import com.vtest.quartz.service.SysJobService;
import com.vtest.quartz.utils.CronUtils;
import com.vtest.quartz.utils.constants.Constants;
import com.vtest.quartz.utils.excel.ExcelUtil;
import com.vtest.quartz.utils.exception.TaskException;
import com.vtest.quartz.utils.others.StringUtils;
import com.vtest.quartz.utils.quartz.ScheduleUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @program: Quartz
 * @author: tiger
 * @create: 2024-12-13 16:15
 * @Description :调度任务信息操作处理
 */
@Slf4j
@RestController
@RequestMapping("/job")
public class SysJobController {

    @Autowired
    private SysJobService jobService;

    /**
     * 刷新定时任务
     */
    @RequestMapping("/refresh")
    public String refreshJob() throws SchedulerException, TaskException {
        log.debug("开始刷新任务");
        jobService.init();
        log.debug("刷新任务结束");
        return "刷新成功";
    }

    /**
     * 导出定时任务列表
     */
    @RequestMapping("/export")
    public void export(HttpServletResponse response) {
        List<SysJob> list = jobService.selectJobList();
        System.out.println(list);
        ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
        util.exportExcel(response, list, "定时任务");
    }

    /**
     * 新增定时任务
     */
    @RequestMapping("/add")
    public String add(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return "新增任务'" + job.getJobName() + "'失败，Cron表达式不正确";
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constants.LOOKUP_RMI)) {
            return "新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用";
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.LOOKUP_LDAP, Constants.LOOKUP_LDAPS})) {
            return "新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用";
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[]{Constants.HTTP, Constants.HTTPS})) {
            return "新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用";
        } else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constants.JOB_ERROR_STR)) {
            return "新增任务'" + job.getJobName() + "'失败，目标字符串存在违规";
        } else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return "新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内";
        }
        job.setCreateBy("tiger");
        jobService.insertJob(job);
        return "新增成功";
    }


}
